package com.sky.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class GithubStorageUtil {

    @Value("${github.repo}")
    private String githubRepo;

    @Value("${github.token}")
    private String githubToken;

    @Value("${github.branch}")
    private String branch;

    @Value("${github.cdn-url}")
    private String cdnUrl;

    private final RestTemplate restTemplate;

    public GithubStorageUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 上传文件到 GitHub 仓库
     * @param file 要上传的文件
     * @return 文件的 CDN 访问地址
     * @throws IOException 如果文件处理失败
     */
    public String upload(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID() + extension;

        // 将文件内容转换为 Base64
        byte[] fileBytes = file.getBytes();
        String content = Base64.getEncoder().encodeToString(fileBytes);

        // 构建 GitHub API URL
        String apiUrl = "https://api.github.com/repos/" + githubRepo + "/contents/" + filename;

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(githubToken);
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/vnd.github.v3+json");

        // 构建请求体
        Map<String, Object> body = new HashMap<>();
        body.put("message", "Upload file via API");
        body.put("content", content);
        body.put("branch", branch);

        // 创建请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送 PUT 请求
        ResponseEntity<Map> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.PUT,
                requestEntity,
                Map.class
        );

        // 检查响应状态
        if (response.getStatusCode() == HttpStatus.CREATED) {
            log.info("文件成功上传到 GitHub: {}", filename);
            // 返回 CDN 访问地址
            return cdnUrl + "/" + filename;
        } else {
            log.error("GitHub 文件上传失败: {}", response.getBody());
            throw new IOException("GitHub 文件上传失败，状态码: " + response.getStatusCode());
        }
    }
}